package com.xiaolin.io;

import java.io.*;

/**
 * @ClassName TestObjectInputStream
 * @Description TODO
 * @Detail 对象输入输出流
 * @Author MyPC
 * @Date 2020/9/26
 * @Version 1.0
 */
public class TestObjectInputStream {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        Student student=new Student();
        student.setAge(18);
        student.setName("小林哈哈");
        boolean b = objectToFile(student);
        System.out.println(b);
        Student stu = (Student) fileToObject("D:\\1file\\object.txt");
        System.out.println(stu.toString());
    }

    /**
     * 将对象序列化写到文件中
     * 注：对象要实现序列化接口
     * @param object
     * @return
     */
    public static boolean objectToFile(Object object){
        ObjectOutputStream objectOutputStream =null;
        try {
            objectOutputStream=new ObjectOutputStream(new FileOutputStream("D:\\1file\\object.txt"));
            objectOutputStream.writeObject(object);
            return true;
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(objectOutputStream != null){
                try {
                    objectOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
        return false;
    }

    /**
     * 将文件的对象进行反序列化
     * @param origin
     * @return
     */
    public static Object fileToObject(String origin) {
        ObjectInputStream objectInputStream=null;
        try {
            objectInputStream=new ObjectInputStream(new FileInputStream(origin));
            return objectInputStream.readObject();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            if(objectInputStream != null){
                try {
                    objectInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

}

class Student implements Serializable{
    int age;
    String name;

    public void setAge(int age) {
        this.age = age;
    }

    public int getAge() {
        return age;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    @Override
    public String toString() {
        return "年龄："+age+"名字："+name;
    }
}
